import { Express, RequestHandler, Router } from "express";
import svgCaptcha, { ConfigObject } from "svg-captcha";
import { random16Color } from "./number";
export const printRoutes = (app: Express) => {
    interface Layer {
        route?: {
            path: string;
            stack: Array<{ handle: RequestHandler }>;
        };
        name: string;
        handle: (RequestHandler | Router) & { stack: Layer[] };
        method?: string; // HTTP method
        regexp?: RegExp | string | { fast_slash: boolean }; // 处理的正则表达式
    }
    let routesNum = 0;
    const print = (path: string[], layer: Layer) => {
        if (layer.route) {
            layer.route.stack.forEach(subLayer => print(path.concat(split(layer.route!.path)), subLayer as Layer));
        } else if (layer.name === "router" && layer.handle.stack) {
            layer.handle.stack.forEach((subLayer: Layer) => print(path.concat(split(layer.regexp as string)), subLayer));
        } else if (layer.method) {
            routesNum += 1;
            console.log(
                "%s /%s",
                layer.method.toUpperCase(),
                path
                    .concat(split(layer.regexp as string))
                    .filter(Boolean)
                    .join("/")
            );
        }
    };

    const split = (thing: string | { fast_slash: boolean }) => {
        if (typeof thing === "string") {
            return thing.split("/");
        } else if (thing.fast_slash) {
            return "";
        } else {
            var match = thing
                .toString()
                .replace("\\/?", "")
                .replace("(?=\\/|$)", "$")
                .match(/^\/\^((?:\\[.*+?^${}()|[\]\\\/]|[^.*+?^${}()|[\]\\\/])*)\$\//);
            return match ? match[1].replace(/\\(.)/g, "$1").split("/") : "<complex:" + thing.toString() + ">";
        }
    };

    app._router.stack.forEach((layer: Layer) => print([], layer));
    console.log(`共${routesNum}条路由`);
};

export const getCaptcha = (options?: ConfigObject) => {
    const getColor = (): string => {
        const color = random16Color();
        if (isLightOrDark(color) === "light") return color;
        return getColor();
    };
    if (!options) options = { width: 95, height: 31, size: 4, fontSize: 50, background: getColor(), color: true };
    return svgCaptcha.create(options);
};

export const hexToRgb = (hex: string): { r: number; g: number; b: number } | null => {
    // 去掉 # 号
    hex = hex.replace(/^#/, "");

    // 如果是3位长度的颜色码，扩展为6位
    if (hex.length === 3) {
        hex = hex
            .split("")
            .map(char => char + char)
            .join("");
    }

    // 解析颜色码
    const bigint = parseInt(hex, 16);
    if (isNaN(bigint) || hex.length !== 6) return null;

    const r = (bigint >> 16) & 255;
    const g = (bigint >> 8) & 255;
    const b = bigint & 255;

    return { r, g, b };
};

export const getBrightness = (r: number, g: number, b: number): number => {
    // 亮度公式
    return 0.299 * r + 0.587 * g + 0.114 * b;
};

export const isLightOrDark = (hexColor: string): "light" | "dark" | null => {
    const rgb = hexToRgb(hexColor);
    if (!rgb) return null;

    const brightness = getBrightness(rgb.r, rgb.g, rgb.b);
    // 你可以调整这个阈值来改变亮暗的判断标准
    return brightness > 150 ? "light" : "dark";
};

/**
 * Promise延迟
 *
 * @param {number} delay - 指定延迟时间
 * @returns {Promise} - Promise对象
 */
export const sleep = (delay = 0) => new Promise(resolve => setTimeout(resolve, delay));
